﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Xml;
using System.Collections.Specialized;

namespace Xinnos.Lca.Yacht.Analyzer.View
{
    internal class ObjectViewModel:WorkBreakdownStructureViewModel,INotifyPropertyChanged
    {
        public ObservableCollection<ComponentRatioViewModel> Ratios { get; set; }
        public ObservableCollection<ObjectRateViewModel> Rates { get; set; }
        private ComponentRatioViewModel mRatio = null;
        public ComponentRatioViewModel Ratio
        {
            get { return mRatio; }
            set
            {
                mRatio = value;
                RaisePropertyChanged("Ratio");
            }
        }

        public override XmlElement Export(XmlDocument doc)
        {
            XmlElement _element = base.Export(doc);
            if (null == _element) return _element;
            if (0 < Ratios.Count)
            {
                XmlElement _ratios = doc.CreateElement("Areas");
                foreach (ComponentRatioViewModel _ratio in Ratios)
                {
                    XmlElement _child = _ratio.Export(doc);
                    if (null != _child) _ratios.AppendChild(_child);
                }
                _element.AppendChild(_ratios);
            }
            return _element;
        }
        public override void Import(XmlElement element)
        {
            base.Import(element);
            Ratios.Clear();
            if (element.HasChildNodes)
            {
                foreach (XmlElement _child in element.ChildNodes)
                {
                    if ("Areas" == _child.Name)
                    {
                        if (_child.HasChildNodes)
                        {
                            foreach (XmlElement _ratio in _child.ChildNodes)
                            {
                                ComponentRatioViewModel _rate = new ComponentRatioViewModel();
                                _rate.Import(_ratio);
                                Ratios.Add(_rate);
                            }
                        }
                    }
                }
            }
        }

        public ObjectViewModel()
            : base()
        {
            if (null == Rates) Rates = new ObservableCollection<ObjectRateViewModel>();
            if (null == Ratios) Ratios = new ObservableCollection<ComponentRatioViewModel>();
            Ratios.CollectionChanged += OnRatiosChanged;
            foreach (ComponentRatioViewModel _ratio in Ratios) _ratio.PropertyChanged += OnRatioChanged;
        }

        public IEnumerable<ObjectRateViewModel> Calculate()
        {
            List<ObjectRateViewModel> _list = null;
            if (0 < Rates.Count) _list = new List<ObjectRateViewModel>(Rates);
            else
            {
                if (0 < Children.Count)
                {
                    foreach (ObjectViewModel _child in Children)
                    {
                        IEnumerable<ObjectRateViewModel> _rates = _child.Rates;
                        if (null == _rates) _rates = _child.Calculate();
                        foreach (ObjectRateViewModel _rate in _rates)
                        {
                            if (null != _list)
                            {
                                ObjectRateViewModel _current = null;
                                foreach (ObjectRateViewModel _row in _list)
                                {
                                    if (_row.Sequences.Count == _rate.Sequences.Count)
                                    {
                                        bool _matched = true;
                                        for (int i = 0; i < _row.Sequences.Count; i++)
                                        {
                                            if (_row.Sequences[i] != _rate.Sequences[i])
                                            {
                                                _matched = false;
                                                break;
                                            }
                                        }
                                        if (_matched) _current = _row;
                                    }
                                    if (null != _current) break;
                                }
                                if (null == _current)
                                {
                                    _current = new ObjectRateViewModel();
                                    foreach (WorkBreakdownStructureViewModel _structure in _rate.Sequences) _current.Sequences.Add(_structure);
                                    _list.Add(_current);
                                    _current.Rate = _rate.Rate;
                                }
                                else _current.Rate += _rate.Rate;
                            }
                            else
                            {
                                _list = new List<ObjectRateViewModel>();
                                ObjectRateViewModel _newly = new ObjectRateViewModel();
                                foreach (WorkBreakdownStructureViewModel _structure in _rate.Sequences) _newly.Sequences.Add(_structure);
                                _list.Add(_newly);
                                _newly.Rate = _rate.Rate;
                            }
                        }
                    }
                }
                if (null == _list) if (null != this.Parent)
                    {
                        IEnumerable<ObjectRateViewModel> _enumerable = (this.Parent as ObjectViewModel).Calculate();
                        if (null != _enumerable) _list = new List<ObjectRateViewModel>(_enumerable);
                    }
            }
            return _list;
        }

        private void Update()
        {
            // 비율별로 곱하는 것이 아니라, 값을 곱하는 것으로 방법이 바뀌었기 때문에 아래 _total 값 반영 제거
            // 추후 방법이 바뀌거나 옵션에서 선택 기능을 넣을 때를 대비해 주석 처리
            //double _total = 0;
            if (0 < Rates.Count) Rates.Clear();
            foreach (ComponentRatioViewModel _ratio in Ratios)
            {
                if (null == _ratio.Component) return;
                foreach (ComponentRateViewModel _component in _ratio.Component.Rates)
                {
                    ObjectRateViewModel _rate = null;
                    foreach (ObjectRateViewModel _object in Rates)
                    {
                        if (_object.Sequences.Count == _component.Sequences.Count)
                        {
                            bool _matched = true;
                            for (int i = 0; i < _object.Sequences.Count; i++)
                            {
                                if (_object.Sequences[i] != _component.Sequences[i])
                                {
                                    _matched = false;
                                    break;
                                }
                            }
                            if (_matched) _rate = _object;
                        }
                        if (null != _rate) break;
                    }
                    if (null == _rate)
                    {
                        _rate = new ObjectRateViewModel();
                        Rates.Add(_rate);
                        foreach (WorkBreakdownStructureViewModel _structure in _component.Sequences) _rate.Sequences.Add(_structure);
                    }
                    _rate.Rate += _component.Summary * _ratio.Area;
                }
                //_total += _ratio.Ratio;
            }
            //foreach (ObjectRateViewModel _rate in Rates) _rate.Rate /= _total;
        }

        private void OnRatiosChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    foreach (ComponentRatioViewModel _ratio in e.NewItems) _ratio.PropertyChanged += OnRatioChanged;
                    break;
            }
            Update();
        }
        private void OnRatioChanged(object sender, PropertyChangedEventArgs e)
        {
            Update();
        }
    }
}